package com.qhhc.controller;

import com.qhhc.entity.CustomerServiceMessage;
import com.qhhc.entity.CustomerServiceSession;
import com.qhhc.service.CustomerServiceMessageService;
import com.qhhc.service.CustomerServiceSessionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 客服控制器
 */
@RestController
@RequestMapping("/api/customer-service")
public class CustomerServiceController {

    @Autowired
    private CustomerServiceMessageService messageService;

    @Autowired
    private CustomerServiceSessionService sessionService;

    /**
     * 创建会话
     */
    @PostMapping("/sessions")
    public ResponseEntity<Map<String, Object>> createSession(@RequestBody CustomerServiceSession session, HttpServletRequest request) {
        // 设置访客IP
        session.setIpAddress(getIpAddress(request));
        
        // 如果用户未登录，生成一个访客ID
        if (session.getUserId() == null && (session.getVisitorId() == null || session.getVisitorId().isEmpty())) {
            session.setVisitorId(generateVisitorId());
        }
        
        String sessionId = sessionService.createSession(session);
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("sessionId", sessionId);
        result.put("message", "会话创建成功");
        
        return ResponseEntity.ok(result);
    }

    /**
     * 获取会话详情
     */
    @GetMapping("/sessions/{sessionId}")
    public ResponseEntity<Map<String, Object>> getSession(@PathVariable("sessionId") String sessionId) {
        CustomerServiceSession session = sessionService.getSessionBySessionId(sessionId);
        
        Map<String, Object> result = new HashMap<>();
        if (session != null) {
            result.put("code", 200);
            result.put("data", session);
        } else {
            result.put("code", 404);
            result.put("message", "会话不存在");
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 获取用户会话列表
     */
    @GetMapping("/sessions/user/{userId}")
    public ResponseEntity<Map<String, Object>> getUserSessions(@PathVariable("userId") Long userId) {
        List<CustomerServiceSession> sessions = sessionService.getSessionsByUserId(userId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("data", sessions);
        
        return ResponseEntity.ok(result);
    }

    /**
     * 获取访客会话列表
     */
    @GetMapping("/sessions/visitor/{visitorId}")
    public ResponseEntity<Map<String, Object>> getVisitorSessions(@PathVariable("visitorId") String visitorId) {
        List<CustomerServiceSession> sessions = sessionService.getSessionsByVisitorId(visitorId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("data", sessions);
        
        return ResponseEntity.ok(result);
    }

    /**
     * 获取客服会话列表
     */
    @GetMapping("/sessions/service/{serviceId}")
    public ResponseEntity<Map<String, Object>> getServiceSessions(@PathVariable("serviceId") Long serviceId) {
        List<CustomerServiceSession> sessions = sessionService.getSessionsByServiceId(serviceId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("data", sessions);
        
        return ResponseEntity.ok(result);
    }

    /**
     * 更新会话状态
     */
    @PutMapping("/sessions/{sessionId}/status/{status}")
    public ResponseEntity<Map<String, Object>> updateSessionStatus(
            @PathVariable("sessionId") String sessionId,
            @PathVariable("status") Integer status) {
        int rows = sessionService.updateSessionStatus(sessionId, status);
        
        Map<String, Object> result = new HashMap<>();
        if (rows > 0) {
            result.put("code", 200);
            result.put("message", "状态更新成功");
        } else {
            result.put("code", 400);
            result.put("message", "状态更新失败");
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 评价会话
     */
    @PutMapping("/sessions/{sessionId}/evaluate")
    public ResponseEntity<Map<String, Object>> evaluateSession(
            @PathVariable("sessionId") String sessionId,
            @RequestParam("score") Integer score,
            @RequestParam(value = "content", required = false) String content) {
        int rows = sessionService.evaluateSession(sessionId, score, content);
        
        Map<String, Object> result = new HashMap<>();
        if (rows > 0) {
            result.put("code", 200);
            result.put("message", "评价成功");
        } else {
            result.put("code", 400);
            result.put("message", "评价失败");
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 分页获取会话列表
     */
    @GetMapping("/sessions")
    public ResponseEntity<Map<String, Object>> getSessionList(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "keyword", required = false) String keyword) {
        Map<String, Object> params = new HashMap<>();
        params.put("pageNum", (pageNum - 1) * pageSize);
        params.put("pageSize", pageSize);
        
        if (status != null) {
            params.put("status", status);
        }
        
        if (keyword != null && !keyword.isEmpty()) {
            params.put("keyword", keyword);
        }
        
        List<CustomerServiceSession> sessions = sessionService.getSessionList(params);
        int total = sessionService.getSessionCount(params);
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("data", sessions);
        result.put("total", total);
        
        return ResponseEntity.ok(result);
    }

    /**
     * 发送消息
     */
    @PostMapping("/messages")
    public ResponseEntity<Map<String, Object>> sendMessage(@RequestBody CustomerServiceMessage message, HttpServletRequest request) {
        // 设置IP地址
        message.setIpAddress(getIpAddress(request));
        
        // 设置消息状态为未读
        if (message.getStatus() == null) {
            message.setStatus(0);
        }
        
        int rows = messageService.sendMessage(message);
        
        // 更新会话最后一条消息
        if (rows > 0) {
            sessionService.updateSessionLastMessage(message.getSessionId(), message.getContent());
        }
        
        Map<String, Object> result = new HashMap<>();
        if (rows > 0) {
            result.put("code", 200);
            result.put("message", "消息发送成功");
        } else {
            result.put("code", 400);
            result.put("message", "消息发送失败");
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 获取会话消息列表
     */
    @GetMapping("/messages/{sessionId}")
    public ResponseEntity<Map<String, Object>> getSessionMessages(@PathVariable("sessionId") String sessionId) {
        List<CustomerServiceMessage> messages = messageService.getMessagesBySessionId(sessionId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("data", messages);
        
        return ResponseEntity.ok(result);
    }

    /**
     * 更新消息状态
     */
    @PutMapping("/messages/{id}/status/{status}")
    public ResponseEntity<Map<String, Object>> updateMessageStatus(
            @PathVariable("id") Long id,
            @PathVariable("status") Integer status) {
        int rows = messageService.updateMessageStatus(id, status);
        
        Map<String, Object> result = new HashMap<>();
        if (rows > 0) {
            result.put("code", 200);
            result.put("message", "状态更新成功");
        } else {
            result.put("code", 400);
            result.put("message", "状态更新失败");
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 批量更新会话消息状态
     */
    @PutMapping("/messages/session/{sessionId}/status/{status}")
    public ResponseEntity<Map<String, Object>> updateSessionMessagesStatus(
            @PathVariable("sessionId") String sessionId,
            @PathVariable("status") Integer status) {
        int rows = messageService.updateMessagesStatusBySessionId(sessionId, status);
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "更新了" + rows + "条消息状态");
        
        return ResponseEntity.ok(result);
    }

    /**
     * 获取未读消息数量
     */
    @GetMapping("/messages/unread/{sessionId}/{senderType}")
    public ResponseEntity<Map<String, Object>> getUnreadMessageCount(
            @PathVariable("sessionId") String sessionId,
            @PathVariable("senderType") Integer senderType) {
        int count = messageService.getUnreadMessageCount(sessionId, senderType);
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("count", count);
        
        return ResponseEntity.ok(result);
    }

    /**
     * 获取客户端IP地址
     */
    private String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 如果是多级代理，则取第一个IP地址
        if (ip != null && ip.indexOf(",") > 0) {
            ip = ip.substring(0, ip.indexOf(","));
        }
        return ip;
    }

    /**
     * 生成访客ID
     */
    private String generateVisitorId() {
        return "visitor_" + UUID.randomUUID().toString().substring(0, 8);
    }
} 